import React, { useState, useEffect, useLayoutEffect } from 'react';
import { Button, View, Text, FlatList, Image, StyleSheet, SafeAreaView, Pressable, ScrollView } from 'react-native';
import { useNavigation } from '@react-navigation/native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import axios from 'axios';

function MyselfHeader() {
    return (
        <View style={styles.customHeader}>
            <Text style={styles.headerTitle}>我的</Text>
            {/* 如果需要其他按钮或图标，也可以在这里添加 */}
        </View>
    );
}
function Myself({ navigation }) {
    const [userInfo, setUserInfo] = useState({});
    const [collections, setCollections] = useState('');
    const [postCount, setPostCount] = useState('');
    const [commitCount, setCommitCount] = useState('')
    const [character, setCharacter] = useState('')
    useEffect(() => {
        const unsubscribe = navigation.addListener('focus', () => {
          // 每次页面获得焦点时调用的函数
          reloadPage();
        });
    
        // 组件卸载时取消监听
        return unsubscribe;
      }, [navigation]);
    const reloadPage = async () => {
        // 这里放置重新加载页面的逻辑
        // 例如清空状态或重新获取数据
        setUserInfo({});
        setCollections('');
        setPostCount('');
        setCommitCount('');
        setCharacter('');
        
        // 重新获取用户信息和数据
        const userinfo = await AsyncStorage.getItem('userInfo');
        if (userinfo) {
          setUserInfo(JSON.parse(userinfo));
        }
        getcollections();
        getPostCounts();
        getCommitCounts();
        getUserCharacter();
      };
    const getcollections = async () => {
        axios.get('http://47.111.227.58:3000/dynamic/getUserCollectedDynamicsCount', {
            params: {
                username: userInfo.username
            },
        })
            .then(res => {
                // console.log(res.data);
                setCollections(res.data.count);
            })
            .catch(error => {
                console.error('Error:', error);
            });
    };
    const getPostCounts = async () => {
        axios.get('http://47.111.227.58:3000/dynamic/getUserPostedDynamicsCount', {
            params: {
                username: userInfo.username
            },
        })
            .then(res => {
                // console.log(res.data);
                setPostCount(res.data.count);
            })
            .catch(error => {
                console.error('Error:', error);
            });
    };
    const getCommitCounts = async () => {
        axios.get('http://47.111.227.58:3000/dynamic/getUserPostedCommentsCount', {
            params: {
                username: userInfo.username
            },
        })
            .then(res => {
                // console.log(res.data);
                setCommitCount(res.data.count);
            })
            .catch(error => {
                console.error('Error:', error);
            });
    };
    const getUserCharacter = async () => {
        axios.get('http://47.111.227.58:3000/dynamic/getUserCharacter', {
            params: {
                username: userInfo.username
            },
        })
            .then(res => {
                // console.log(res.data.results[0].characters);
                setCharacter(res.data.results[0].characters);
            })
            .catch(error => {
                console.error('Error:', error);
            });
    };
    
    useEffect(() => {
        (async () => {
            const userinfo = await AsyncStorage.getItem('userInfo');
            if (userinfo) {
                setUserInfo(JSON.parse(userinfo));
                // console.log(JSON.parse(userinfo))
            }
            // console.log(userinfo)
        })();
    }, []);
    useEffect(() => {
        (async () => {
            if (userInfo.username) {
                getcollections()
                getPostCounts()
                getCommitCounts()
                getUserCharacter()
            }
        })();
    }, [userInfo]);

    useLayoutEffect(() => {
        navigation.setOptions({
            headerShown: true, // 显示头部
            headerStyle: {
                backgroundColor: '#EB7A76', // 设置头部背景颜色#EB7A76
                borderColor: '#EB7A76', // 设置头部边框颜色
            },
            headerTitleStyle: {
                color: '#fff', // 设置头部标题颜色
                height: 30,
            },
            headerTitle: '我的', // 设置头部标题
            // 这里可以继续添加其他头部相关的设置
        });
    }, [navigation]);

    return (

        <View style={styles.container}>
            {/* <MyselfHeader /> */}
            {/* <View style={styles.header}> */}
            <ScrollView>
                <View
                    style={styles.header}
                >
                    <Pressable onPress={() => navigation.navigate('主页')}>
                        <View style={styles.profileInfo}>
                            <Image style={styles.avatar} source={{ uri: userInfo.imgUrl }} />
                            <Text style={styles.name}>{userInfo.username}</Text>
                        </View>
                    </Pressable>
                    <View style={styles.statsRow}>
                        <View style={styles.statItem}>
                            <Text style={styles.statLabel}>人品</Text>
                            <Text style={styles.statValue}>{character}</Text>

                        </View>
                        <Pressable onPress={() => navigation.navigate('我的收藏')}>
                            <View style={styles.statItem}>
                                <Text style={styles.statLabel}>收藏</Text>
                                <Text style={styles.statValue}>{collections}</Text>
                            </View>
                        </Pressable>
                        <Pressable onPress={() => navigation.navigate('我的帖子')}>
                            <View style={styles.statItem}>
                                <Text style={styles.statLabel}>帖子</Text>
                                <Text style={styles.statValue}>{postCount}</Text>
                            </View>
                        </Pressable>
                        <Pressable onPress={() => navigation.navigate('我的评论')}>
                            <View style={styles.statItem}>
                                <Text style={styles.statLabel}>评论</Text>
                                <Text style={styles.statValue}>{commitCount}</Text>
                            </View>
                        </Pressable>
                    </View>
                </View>
                {/* </View> */}

                <View style={{ flex: 1 }}>
                    {/* 顶部区域 */}
                    <View style={styles.topvip}>
                        <View>
                            <Text style={{ color: '#8B6914', fontWeight: 'bold', fontSize: 18 }}>朵朵会员</Text>
                            <Text style={{ color: '#8B6914' }}>免费领取朵朵会员体验卡，尽享权益</Text>
                        </View>

                        <Pressable style={{ backgroundColor: '#363636', padding: 10, borderRadius: 10 }}>
                            <Text style={{ color: 'white', fontWeight: 'bold' }}>免费领取</Text>
                        </Pressable>
                    </View>

                    {/* 中间区域 */}
                    <View style={styles.shopmall}>
                        <View style={{ alignItems: 'center', flexDirection: 'row', justifyContent: 'space-between' }}>
                            <View>
                                <Text style={{ color: '#FF6A6A', fontWeight: 'bold', fontSize: 18 }}>朵朵商城</Text>
                                <Text style={{ color: '#FF6A6A' }}>人品值兑换好礼</Text>
                            </View>

                            <Image source={require('../assets/gift_iocn.png')} style={{ width: 45, height: 45, marginLeft: 5 }} />
                        </View>
                        <View style={{ height: '100%', width: 1, backgroundColor: '#D3D3D3', marginHorizontal: 10 }} />
                        <View style={{ alignItems: 'center', flexDirection: 'row', justifyContent: 'space-between' }}>
                            <View>
                                <Text style={{ color: '#1E90FF', fontWeight: 'bold', fontSize: 18 }}>人品抽奖</Text>
                                <Text style={{ color: '#1E90FF' }}>试试手气抽个奖</Text>
                            </View>

                            <Image source={require('../assets/compass_iocn.png')} style={{ width: 45, height: 45, marginLeft: 5 }} />
                        </View>
                    </View>


                </View>


                <View style={styles.menuContainer}>
                    {/* <Image style={styles.vip} source={require('./assets/jifen.png')} resizeMode="contain" /> */}
                    <MenuItem icon={require('../assets/shequ.png')} text="社区规范" />
                    <MenuItem icon={require('../assets/xinshou.png')} text="新手帮助" />
                    <MenuItem icon={require('../assets/yaoqing.png')} text="邀请校友" isLastItem={true} />
                </View>
                <View style={styles.menuContainer}>
                    <Pressable onPress={() => navigation.navigate('系统设置')}>
                        <MenuItem icon={require('../assets/shezhi.png')} text="设置" isLastItem={true} />
                    </Pressable>
                </View>
                <View style={styles.menuContainer}>
                    <MenuItem icon={require('../assets/guanyu.png')} text="关于我们" />
                    <MenuItem icon={require('../assets/yijian.png')} text="意见反馈" isLastItem={true} />
                </View>

            </ScrollView >

        </View >
    );
}

function MenuItem({ icon, text, isLastItem }) {
    return (
        <View style={[styles.menuItem, isLastItem && styles.lastItem]}>
            <Image style={styles.menuIcon} source={icon} />
            <Text style={styles.menuText}>{text}</Text>
            <Image style={styles.arrowIcon} source={require('../assets/jiantou.jpg')} />
        </View>
    );
}



const styles = StyleSheet.create({
    customHeader: {
        height: 50, // 根据需要调整高度
        backgroundColor: '#EB7A76', // 头部背景颜色
        alignItems: 'center',
        justifyContent: 'center',
    },
    headerTitle: {
        color: '#fff', // 标题颜色
        fontSize: 20, // 标题字体大小
        fontWeight: 'bold',
    },
    statsRow: {
        flexDirection: 'row',
        justifyContent: 'space-around',
        alignItems: 'center',
    },
    statItem: {
        flexDirection: 'column',
        alignItems: 'center',
        margin: 20,
    },
    statValue: {
        fontSize: 18,
        fontWeight: 'bold',
        color: '#ffffff',
    },
    profileInfo: {
        flexDirection: 'row',
        justifyContent: 'flex-start',
        alignItems: 'center',
    },
    statLabel: {
        fontSize: 10,
        fontWeight: 'normal',

        color: '#FFFAF0',
    },
    container: {
        flex: 1,
        backgroundColor: '#f0f0f0',//#f0f0f0

    },
    header: {//头部
        height: 180,
        // marginTop: 0,
        backgroundColor: '#EB7A76',
        // alignItems: 'center',
        justifyContent: 'center',
        borderBottomWidth: 0,
        borderBottomColor: '#EB7A76',
        borderColor: '#EB7A76', // 临时边框颜色
        borderWidth: 0, // 临时边框宽度
    },
    avatar: {
        width: 70,
        height: 70,
        borderRadius: 35,
        marginBottom: 10,
        marginLeft: 20,
    },
    name: {
        fontSize: 18,
        color: '#ffffff',
        marginLeft: 20,
        fontWeight: 'bold',
    },
    topvip: {//朵朵会员
        borderWidth: 1,
        borderColor: '#FFDEAD',
        flexDirection: 'row',
        justifyContent: 'space-between',
        backgroundColor: '#FDF5E6',
        borderRadius: 10,
        padding: 20,
        margin: 10,
        marginBottom: 3,
        marginTop: 5,
        marginLeft: 8,
        marginRight: 8,
    },
    shopmall: {//朵朵商城
        borderWidth: 1,
        backgroundColor: '#FFF',
        borderColor: '#D3D3D3',
        flexDirection: 'row',
        justifyContent: 'space-between',
        borderRadius: 10,
        padding: 20,
        margin: 10,
        marginTop: 3,
        marginBottom: 3,
        marginLeft: 8,
        marginRight: 8,
    },
    button: {
        backgroundColor: '#EB7A76', // 按钮背景色
        padding: 10, // 按钮内边距
        borderRadius: 5, // 按钮圆角
        marginLeft: 10, // 按钮左边距
    },
    buttonText: {
        color: '#ffffff', // 按钮文字颜色
        fontWeight: 'bold', // 按钮文字粗细
    },
    menuContainer: {//社区规范等
        borderWidth: 1,
        borderColor: '#ffffff',
        borderRadius: 10,
        padding: 8,
        marginVertical: 3,
        backgroundColor: '#ffffff',
        margin: 10,
        marginTop: 3,
    },
    menuItem: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        paddingVertical: 10,
        borderBottomWidth: 1,
        borderBottomColor: '#EFEFEF',
    },
    lastItem: {
        borderBottomWidth: 0, // 移除底部边框
    },
    menuIcon: {
        width: 20,
        height: 20,
        marginRight: 10,
    },
    menuText: {
        flex: 1,
        fontSize: 16,
        // ... 根据图片调整样式 ...
    },
    arrowIcon: {
        width: 16,
        height: 16,
    }
});

export default Myself;
